<template>
  <div class="dashboard-container">
    <div class="app-container">
      <!-- 靠右的按钮 -->
      <page-tools>
        <el-button type="primary" size="small" @click="openDialog(1,0)">添加权限</el-button>
      </page-tools>
      <!--  树形表格，数据必须式树形的上下级结构的； 下级数据需要放在children里面； 添加row-key树形，值为唯一字段名  -->
      <el-table row-key="id" :data="list" border>
        <el-table-column prop="name" align="center" label="名称"/>
        <el-table-column prop="code" align="center" label="标识"/>
        <el-table-column prop="description" align="center" label="描述"/>
        <el-table-column align="center" label="操作">
          <template slot-scope="scope">
            <el-button type="text" @click="openDialog(2,scope.row.id)">添加</el-button>
            <el-button type="text" @click="editRow(scope.row.id)">编辑</el-button>
            <el-button type="text" @click="delRow(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--新增，修改权限组件-->
      <add-perm ref="addPerm" @update="initData"/>
    </div>
  </div>
</template>
<script>
import { delPermissionApi, getPermissionListApi } from '@/api/permission'
import { tranListToTreeData } from '@/utils'
import AddPerm from '@/views/permissions/components/addPerm.vue'

export default {
  name: 'Permission',
  components: {
    AddPerm
  },
  data() {
    return {
      list: []
    }
  },
  created() {
    this.initData()
  },
  methods: {
    // 获取权限列表
    async initData() {
      const res = await getPermissionListApi()
      this.list = tranListToTreeData(res, '0')
    },
    // 打开弹窗
    openDialog(type, pid) {
      // type 是类型， pid是父级id
      this.$refs.addPerm.dialogShow = true
      this.$refs.addPerm.formData.type = type
      this.$refs.addPerm.formData.pid = pid
    },
    // 编辑
    editRow(id) {
      console.log(id)
      this.$refs.addPerm.getRowInfo(id)
    },
    // 删除
    async delRow(id) {
      console.log(id)
      try {
        await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
      } catch (error) {
        return this.$message({
          type: 'info',
          message: '已取消删除'
        })
      }
      await delPermissionApi(id)
      this.$message.success('删除成功')
      await this.initData()
    }
  }
}
</script>
<style></style>
